package com.zd.hamster.sys.util;

import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

/**
 * 图片工具
 * @author zhang
 *
 */
public class ImageUtils {
	
	private final static Logger log = LoggerFactory.getLogger(ImageUtils.class);
	
	public static String[] formatNames = new String[] {"png", "jpg", "jpeg", "bmp"};
	
	/**
	 * 判断文件格式是否是图片
	 * @param filename
	 * @return
	 */
	public static boolean isImage(String filename) {
		String suf = filename.substring(filename.lastIndexOf(".") + 1);
		for (String formatName : formatNames) {
			if(formatName.equalsIgnoreCase(suf)) {
				return true;
			}
		}
		return false;
	}
	
	/**
	/**
	 * 按比率缩放 size为文件大小
	 * @param src
	 * @param dest
	 * @param size 以K为单位
	 * @throws IOException 
	 * @throws Exception
	 */
//	public static void zoomImage(MultipartFile src, File dest, Integer size) throws IOException {
//		long fileSize = src.getSize();
//		if (fileSize < size * 1024) { // 文件大于size k时，才进行缩放,注意：size以K为单位
//			src.transferTo(dest);
//			return;
//		}
//		Double rate = (size * 1024d ) / fileSize; // 获取长宽缩放比例
//		rate = 1d;
//		BufferedImage bufImg = ImageIO.read(src.getInputStream());
//		AffineTransformOp ato = new AffineTransformOp(AffineTransform.getScaleInstance(rate, rate), null);
//		BufferedImage srcFilter = ato.filter(bufImg, null);
//		String formatName = dest.getName().substring(dest.getName().lastIndexOf(".") + 1);
//		ImageIO.write(srcFilter, formatName, dest);
//	}
	
	/**
	 * 
	 * @param src
	 * @param dest
	 * @param maxWidth
	 * @param maxHeight
	 * @return
	 * @throws IOException
	 */
	public static boolean zoomScalingImage(MultipartFile src, File dest, int maxWidth, int maxHeight) throws IOException {
		//读取图片
		BufferedImage bufImg = ImageIO.read(src.getInputStream());
		if(bufImg.getWidth() <= maxWidth && bufImg.getHeight() <= maxHeight) {
			return false;
		}
		//计算缩放比例
		double rate = bufImg.getWidth() > bufImg.getHeight() ? maxWidth * 1d / bufImg.getWidth() :  maxHeight * 1d / bufImg.getHeight();
		//按比例设置新图长宽（不超过最大宽度和最大高度）
		//https://blog.csdn.net/sinolzeng/article/details/42008291
		//设置图片质量
		RenderingHints hints = new RenderingHints(RenderingHints. KEY_ANTIALIASING, RenderingHints. VALUE_ANTIALIAS_ON);
		hints.put(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
		hints.put(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
		//设置图片缩放
		AffineTransformOp ato = new AffineTransformOp(AffineTransform.getScaleInstance(rate, rate), hints);
		BufferedImage itemp = ato.filter(bufImg, null);
		//设置图片类型
		String formatName = dest.getName().substring(dest.getName().lastIndexOf(".") + 1).toLowerCase();
		boolean result = ImageIO.write((BufferedImage) itemp, formatName, dest);
		if(!result) log.warn("ImageIO.write() return false ! File - " + src.getOriginalFilename() + " | dest - " + dest.getAbsolutePath());
		return result;
	}

	/**
	 * 按固定长宽进行缩放
	 * @param src
	 * @param dest
	 * @param formatName 生成的格式
	 * @param width
	 * @param height
	 * @throws IOException
	 */
//	public static void zoomImage(MultipartFile src, File dest, int width, int height) throws IOException  {
//		BufferedImage bufImg = ImageIO.read(src.getInputStream()); // 读取图片
//		double wr = width * 1.0 / bufImg.getWidth(); // 获取缩放比例
//		double hr = height * 1.0 / bufImg.getHeight();
//		Image itemp = bufImg.getScaledInstance(width, height, BufferedImage.SCALE_SMOOTH);// 设置缩放目标图片模板
//		AffineTransformOp ato = new AffineTransformOp(AffineTransform.getScaleInstance(wr, hr), null);
//		itemp = ato.filter(bufImg, null);
//		//写入缩减后的图片
//		Graphics2D g = null;
//		String formatName = dest.getName().substring(dest.getName().lastIndexOf(".") + 1).toLowerCase();
//		try {
//			for(;!ImageIO.write((BufferedImage) itemp, formatName, dest);) {
//				//如果写入失败，则用如下方式再转换一次
//				if(null != g)
//					throw new IllegalArgumentException(String.format("not found writer for '%s'",formatName));
//				g = itemp.createGraphics();
//				g.drawImage(bufImg, 0, 0, null);
//			}
//		} finally {
//			if(g != null) {
//				g.dispose();
//			}
//		}
//	
//	}


}
